package com.edu.d10_test;

import java.util.List;
import java.util.Random;

/**
 * 操作线程子类，每个线程对象的操作
 */
public class PeopleThread2 extends Thread{
    private List<Integer> moneys;
    private int totalMoney;

    public PeopleThread2(List<Integer> moneys, String name) {
        super(name);
        this.moneys = moneys;
    }

    public int getTotalMoney() {
        return totalMoney;
    }

    public void setTotalMoney(int totalMoney) {
        this.totalMoney = totalMoney;
    }

    private Random r=new Random();//线程的具体操作

    @Override
    public void run() {
        //100个线程来抢
      while (true){
          String name1 = Thread.currentThread().getName();
          synchronized (moneys){
              if(moneys.size()==0){
                  //代表红包抢没了
                  break;
              }
              //取红包给抢到的这个人,remove()，去除集合中的元素并返回删除值
              Integer removed = moneys.remove(r.nextInt(moneys.size()));
              System.out.println(name1+"抢到了"+removed);
              totalMoney+=removed;
              try {
                  Thread.sleep(10);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
    }
}
}
